package com.xiaofeng.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.xiaofeng.subject.common.enums.IsDeletedFlagEnum;
import com.xiaofeng.subject.domain.convert.SubjectCategoryConverter;
import com.xiaofeng.subject.domain.entity.SubjectCategoryBO;
import com.xiaofeng.subject.domain.entity.SubjectLabelBO;
import com.xiaofeng.subject.domain.service.SubjectCategoryDomainService;
import com.xiaofeng.subject.domain.util.CacheUtil;
import com.xiaofeng.subject.infra.basic.entity.SubjectCategory;
import com.xiaofeng.subject.infra.basic.entity.SubjectLabel;
import com.xiaofeng.subject.infra.basic.entity.SubjectMapping;
import com.xiaofeng.subject.infra.basic.service.SubjectCategoryService;
import com.xiaofeng.subject.infra.basic.service.SubjectLabelService;
import com.xiaofeng.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2024/01/23/20:26
 * @Description:
 */
@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService{

    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil CacheUtil;

    /**
     * 添加分类
     * @param subjectCategoryBO
     */
    public void add(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryController.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectCategory> SubjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBO> boList = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(SubjectCategoryList);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryDomainServiceImpl.queryPrimaryCategory.boList:{}", JSON.toJSONString(boList));
        }
        boList.forEach(bo -> {
           Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
           bo.setCount(subjectCount);
        });
        return boList;
    }

    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0 ;
    }

    /**
     * 删除分类(逻辑删除)
     * @param subjectCategoryBO
     * @return
     */
    public Boolean delete(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        //定义本地缓存key
        String cacheKey = "CategoryAndLabel."+subjectCategoryBO.getId();
        List<SubjectCategoryBO> subjectCategoryBOS = CacheUtil.getResult(cacheKey, SubjectCategoryBO.class,
                (key) -> getSubjectCategoryBOS(id));
        //查询当前大类下的所有分类
        return subjectCategoryBOS;
    }

    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        //查询分类集合
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if(log.isInfoEnabled()){
            log.info("SubjectCategoryDomainServiceImpl.queryCategoryAndLabel.boList:{}", JSON.toJSONString(subjectCategoryList));
        }
        //将SubjectCategory转换为SubjectCategoryBO
        List<SubjectCategoryBO> categoryBOList = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> completableFutureList = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(category),labelThreadPool)
        ).collect(Collectors.toList());
        for (CompletableFuture<Map<Long, List<SubjectLabelBO>>> future : completableFutureList) {
            try {
                Map<Long, List<SubjectLabelBO>> longListMap = future.get();
                if (CollectionUtils.isEmpty(longListMap)) {
                    continue;
                }
                map.putAll(longListMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // completableFutureList.forEach(future ->{
        //     try {
        //         Map<Long, List<SubjectLabelBO>> resultMap = future.get();
        //         map.putAll(resultMap);
        //     } catch (Exception e) {
        //         e.printStackTrace();
        //     }
        // });
        categoryBOList.forEach(categoryBO ->{
            categoryBO.setLabelBOList(map.get(categoryBO.getId()));
        });
        //返回
        return categoryBOList;
        // //遍历循环
        // //一次性获取标签信息
        // LinkedList<FutureTask<Map<Long,List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
        // //线程池并发调用
        // Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        // categoryBOList.forEach(category ->{
        //     FutureTask<Map<Long,List<SubjectLabelBO>>> futureTask = new FutureTask<>(() ->
        //             getLabelBOList(category));
        //     futureTaskList.add(futureTask);
        //     //提交线程池
        //     labelThreadPool.submit(futureTask);
        // });
        // //遍历循环
        // for(FutureTask<Map<Long,List<SubjectLabelBO>>> futureTask : futureTaskList){
        //     Map<Long, List<SubjectLabelBO>> resultMap = futureTask.get();
        //     if(CollectionUtils.isEmpty(resultMap)){
        //         continue;
        //     }
        //     map.putAll(resultMap);
        // }
    }

    private Map<Long,List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO category) {
        if (log.isInfoEnabled()){
            log.info("getLabelBOList:{}",JSON.toJSONString(category));
        }
        Map<Long,List<SubjectLabelBO>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        //设置分类id
        subjectMapping.setCategoryId(category.getId());
        //通过分类id查询出所有题目关联信息
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)){
            return null;
        }
        //遍历出所有的标签id，保存在集合中
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        //通过标签id进行批量查询
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> labelBOList= new LinkedList<>();
        //forEach遍历循环出标签数据
        labelList.forEach(label ->{
            SubjectLabelBO subjectLabelBO = new SubjectLabelBO();
            //设置标签id
            subjectLabelBO.setId(label.getId());
            //设置标签名称
            subjectLabelBO.setLabelName(label.getLabelName());
            //设置标签所属分类id
            subjectLabelBO.setCategoryId(label.getCategoryId());
            //设置数量
            subjectLabelBO.setSortNum(label.getSortNum());
            labelBOList.add(subjectLabelBO);
        });
        labelMap.put(category.getId(),labelBOList);
        return labelMap;
    }
}
